<?php

	class Activities{
		private $db;
		
		public function __construct(){
			$this->db =& Application::getInstance()->database('default');
		}
		
		/**
		 * 
		 * @param int $userId
		 * @param string $date yyyy-mm-dd
		 * @param string $time hh:mm
		 * @param string $endDate yyyy-mm-dd
		 * @param string $endTime hh:mm
		 * @param string $destType 1 = company, 2 = friend, 3 = city
		 * @param int $destId id of the destination object
		 * @param string $tagId id of the tag (not required)
		 * @return int last insert id
		 */
		public function create($userId, $date, $time, $endDate, $endTime, $destType, $destId, $tagId = null){
			$query = $this->db->query('
				INSERT INTO activities(
					date, time, endDate, endTime, destType, destId, tagId, createdOn, createdBy
				) VALUES (
					:date, :time, :endDate, :endTime, :destType, :destId, :tagId, NOW(), :createdBy
				)
			', array(
				'date' => $date,
				'time' => $time,
				'endDate' => $endDate,
				'endTime' => $endTime,
				'destType' => $destType,
				'destId' => $destId,
				'tagId' => $tagId,
				'createdBy' => $userId
			));
			
			return $query['lastInsertId'];
		}
		
		/**
		 *
		 * @param int $activityId
		 * @param int $userId
		 */
		public function bindUserToActivity($activityId, $userId, $accepted){
			$this->db->query('
				INSERT INTO activitiesUsersLink(
					activityId, userId, accepted
				) VALUES (
					?, ?, ?
				)
			', array(
				$activityId, $userId, $accepted
			));
		}
		
		/**
		 *
		 * @param int $activityId
		 * @param array $users (needs to container id)
		 */
		public function bindMultipleUsersToActivity($activityId, $users){
			$parameters = array();
			$query = '
				INSERT INTO activitiesUsersLink(
					activityId, userId
				) VALUES
			';
			
			foreach($users as &$user){
				$query .= 'VALUES (?, ?), ';
				$parameters[] = $activityId;
				$parameters[] = $user['id'];
			}
			
			$this->db->query(substr($query, 0, -2), $parameters);
		}
		
		/**
		 *
		 * @param string $keyword
		 * @return array id, name
		 */
		public function searchTag($keyword){
			$stmt = $this->db->query('SELECT id, title FROM activitiesTags WHERE title LIKE ?', array('%' . $keyword . '%'));
			
			if($stmt['rowCount'] > 0){
				return $stmt['result'];
			}
			
			return null;
		}
		
		/**
		 *
		 * @param string $name
		 * @return int id
		 */
		public function readTagByName($name){
			$stmt = $this->db->query('SELECT id FROM activitiesTags WHERE title = ?', array($name));
			
			if($stmt['rowCount'] > 0){
				return $stmt['result'][0];
			}
			
			return null;
		}
		
		/**
		 *
		 * @param id $userId
		 * @param string $title
		 * @return int lastInsertId
		 */
		public function createTag($userId, $title){
			$stmt = $this->db->query('INSERT INTO activitiesTags(title, createdOn, createdBy) VALUES (?, NOW(), ?)', array($title, $userId));
			return $stmt['lastInsertId'];
		}
		
		/**
		 *
		 * @param int $userId
		 * @param string $filter used for the date filter (for example "tomorrow", "yesterday") etc.
		 * @param int $limit
		 * @param string $date default = null
		 * @return array
		 */
		public function readHomepageStream($userId, $filter, $limit, $date){
			if($limit >= 350){
				$limit = 350;
			}
			
			$query = '
				SELECT
					A.id as activityId, A.date, A.time, A.endDate, A.endTime,
					A.destType, A.destId, A.createdOn, A.createdBy,
					T.id as tagId, T.title,
					U.id as userId, U.name as userName
				FROM
					usersFriends UF
				JOIN
					activitiesUsersLink AL
				ON
					AL.userId = UF.friendUserId
				JOIN
					users U
				ON
					U.id = AL.userId
				JOIN
					activities A
				ON
					A.id = AL.activityId
				LEFT JOIN
					activitiesTags T
				ON
					T.id = A.tagId
				WHERE
					UF.userId = :userId
				AND
					AL.accepted = 1
			';
			
			$queryFilter = $this->getQueryFilter($filter);
			
			// We have to call the function prepare, because the mysql database class
			// does not support bind values (we need this to pass through the limit as int.
			$stmt = $this->db->prepare($query . $queryFilter . 'ORDER BY A.id DESC LIMIT :limit');
			$stmt->setFetchMode(PDO::FETCH_ASSOC);
			$stmt->bindValue('limit', (int)$limit, PDO::PARAM_INT);
			$stmt->bindValue('userId', $userId);
			
			// If the filter is date...
			if($filter === 'date'){
				$stmt->bindValue('date', $date);
			}
				
			$stmt->execute();
			$activities = $stmt->fetchAll();
			
			$finalActivities = array();
			
			if(count($activities) > 0){
				
				// This merges activities that
				// have multiple users.
				foreach($activities as &$a){
					
					if(!isset($finalActivities[$a['activityId']])){
						$finalActivities[$a['activityId']] = $a;
					} else {
						$finalActivities[$a['activityId']]['withWho'][] = array('name' => $a['userName'], 'id' => $a['userId']);
					}
				}

				$users = new Users();
				$locations = new Locations();
				$activities = array();

				foreach($finalActivities as &$fa){
					if(isset($fa['withWho'])){
						foreach($fa['withWho'] as &$involvedPerson){
							
							// This fixes the problem that the original creator was not first.
							if($involvedPerson['id'] === $fa['createdBy']){
								$friendName = $fa['userName'];
								$friendId = $fa['userId'];
								$person = $involvedPerson;
								$fa['userName'] = $person['name'];
								$fa['userId'] = $person['id'];
								$involvedPerson['name'] = $friendName;
								$involvedPerson['id'] = $friendId;
							}
						}
					}
					
					// Get the object of the activity.
					$obj =& $fa['object'];
					
					// If the object was type 1 (company) get the company.
					if($fa['destType'] === '1'){
						$obj = $locations->readCompany($fa['destId']);
						
					// Get friend.
					} else if($fa['destType'] === '2'){
						if($users->exists($fa['destId'])){
							$obj = $users->read($fa['destId'], array('id', 'name'));
						} else {
							$obj = $users->readUserFriend($userId, $fa['destId']);
						}
					
					// Get city.
					} else if($fa['destType'] === '3'){
						$obj = $locations->readCity($fa['destId']);
					}
					
					$fa = $this->attachMessageHelper($fa);
					
					// Put it back in activities (we need this in order to fix the order).
					$activities[] = $fa;
				}
			}
		
			return $activities;
		}
		
		/**
		 *
		 * @param string $filter
		 * @return string query AND part.
		 */
		private function getQueryFilter($filter){
			$return = '';
			
//			SELECT
//			a.*, u.*,
//			a.date AS activityBeginDate,
//			IF(a.endDate IS NULL, a.date, a.endDate) AS activityEndDate
//			FROM activities
//			JOIN users U ON u.id=a.userId
//			WHERE
//			activityBeginDate <= "yourDesiredEndDate" OR
//			activityEndDate >= "yourDesiredBeginDate"
			
			switch($filter){
				case 'today':
					$return = ' AND DATE(A.date) = DATE(CURDATE())';
					break;
				case 'tomorrow':
					$return = ' AND DATE(A.date) = (CURDATE() + INTERVAL 1 DAY)';
					break;
				case 'yesterday':
					$return = ' AND DATE(A.date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)';
					break;
				case 'nextWeekend':
					$return = " AND UNIX_TIMESTAMP(A.DATE) BETWEEN '" . strtotime('next saturday') . "' AND '" . (strtotime('next monday') - 1) . "'";
					break;
				case 'prevWeekend':
					$return = " AND UNIX_TIMESTAMP(A.DATE) BETWEEN '" . strtotime('previous saturday') . "' AND '" . (strtotime('previous monday') - 1) . "'";
					break;
				case 'date':
					$return = ' AND DATE(A.date) = DATE(:date)';
					break;
			}
			
			return $return;
		}
		
		private function getQueryExtraFilter($displayMales, $displayFemales, $displaySinglesOnly){
			$extraFilter = '';
			
			// Only show males.
			if($displayMales === 'true' && $displayFemales === 'false'){
				$extraFilter = " AND U.sex = 'male'";
				
			// Only show females.
			} else if($displayMales === 'false' && $displayFemales === 'true'){
				$extraFilter = " AND U.sex = 'female'";
			}
			
			// Show singles only.
			if($displaySinglesOnly === 'true'){
				$extraFilter .= " AND U.relationshipStatus = 'single'";
			}
			
			return $extraFilter;
		}
		
		public function readCompanyStream($userId, $companyId, $filter, $limit, $displayMales, $displayFemales, $displayFriendsOnly, $displaySinglesOnly, $date){
			if($displayMales === 'false' && $displayFemales === 'false'){
				return null;
			}
			
			if($limit >= 350){
				$limit = 350;
			}
			
			$query = "
				SELECT
					A.id,
					AL.userId,
					A.date,
					A.time,
					A.endTime,
					A.endDate,
					U.id as userId,
					U.firstName,
					U.name,
					U.birthday,
					U.location,
					U.relationshipStatus
				FROM
					activities A
				JOIN
					activitiesUsersLink AL
				ON
					AL.activityId = A.id
				JOIN
					users U
				ON
					U.id = AL.userId
				WHERE
					A.destType = '1'
				AND
					A.destId = :id
				AND
					AL.accepted = '1'
			";
			
			// We have to call the function prepare, because the mysql database class
			// does not support bind values (we need this to pass through the limit as int.
			$stmt = $this->db->prepare($query . $this->getQueryFilter($filter) . $this->getQueryExtraFilter($displayMales, $displayFemales, $displaySinglesOnly) . 'ORDER BY A.id DESC LIMIT :limit');
			$stmt->setFetchMode(PDO::FETCH_ASSOC);
			$stmt->bindValue('id', $companyId);
			$stmt->bindValue('limit', (int)$limit, PDO::PARAM_INT);
			
			if($filter === 'date'){
				$stmt->bindValue('date', $date);
			}
			
			$stmt->execute();
			$activities = $stmt->fetchAll();
			
			foreach($activities as &$a){
				$a = $this->attachMessageHelper($a);
				
				$a['age'] = getAge($a['birthday']);
				
				if($displayFriendsOnly === 'true'){
					$users = new Users();
					
					if(!$users->isFriendWith($userId, $a['userId'])){
						unset($a);
					}
				}
			}
			
			return $activities;
		}
		
		private function attachMessageHelper($a){
			// Now we have to build message helper, which will help the clients to build the correct
			// string for the message for example: not 28-01-2011 but today, or yesterday etc.
			$fixedDate = explode('-', $a['date']);
			$hours = 0;
			$minutes = 0;
			
			if($a['time'] !== null){
				$fixedTime = explode(':', $a['time']);
				$hours = $fixedTime[0];
				$minutes = $fixedTime[1];
			}

			$sDate = new Date($fixedDate[0], $fixedDate[1], $fixedDate[2], $hours, $minutes, 0);
			$msgHlpr =& $a['messageHelper'];
			$msgHlpr[0] = 'gaat';

			if(!$sDate->isInFuture('now')){
				$msgHlpr[0] = 'ging';
			}

			// If in current week (short day name)
			if($sDate->isToday()){
				$msgHlpr[0] = 'gaat';
				$msgHlpr[1] = 'vandaag';
			} else if($sDate->isYesterday()){
				$msgHlpr[1] = 'gisteren';
			} else if($sDate->isTomorrow()){
				$msgHlpr[1] = 'morgen';
			}
			
			if(isset($a['withWho'])){
				if($msgHlpr[0] === 'gaat'){
					$msgHlpr[0] = 'gaan';
				} else {
					$msgHlpr[0] = 'gingen';
				}
			}
			
			if(!isset($msgHlpr[1])){
				$msgHlpr[2] = $sDate->dayToString();

				if($sDate->isInNextWeek()){
					$msgHlpr[2] = 'volgende week ' . $msgHlpr[2];
				}

				if($sDate->isInPrevWeek()){
					$msgHlpr[2] = 'vorige week ' . $msgHlpr[2];
				}

				if(!$sDate->isInCurrentYear()){
					$msgHlpr[2] = $msgHlpr[2] . ' ' . $sDate->getDay() . ' ' . $sDate->getMonthString() . ' ' . $sDate->getYear();
				} else if(!$sDate->isInCurrentWeek()){
					$msgHlpr[2] = $msgHlpr[2] . ' ' . $sDate->getDay() . ' ' . $sDate->getMonthString();
				}
			}
			
			if($a['endDate'] !== null){
				$fixedEDate = explode('-', $a['endDate']);
				$hours = 0;
				$minutes = 0;
			
				if($a['endTime'] !== null){
					$fixedETime = explode(':', $a['endTime']);
					$hours = $fixedETime[0];
					$minutes = $fixedETime[1];
				}

				$eDate = new Date($fixedEDate[0], $fixedEDate[1], $fixedEDate[2], $hours, $minutes, 0);
				
				// Mike Vercoelen en Eva Collier gaan vandaag tot volgende week zaterdag naar Amsterdam.
				
				if($eDate->isToday()){
					$msgHlpr[3] = 'vandaag';
				} else if($eDate->isYesterday()){
					$msgHlpr[3] = 'gisteren';
				} else if($eDate->isTomorrow()){
					$msgHlpr[3] = 'morgen';
				} else if($eDate->isDayAfterTomorrow()){
					$msgHlpr[3] = 'overmorgen';
				} else if($eDate->isDayBeforeYesterday()){
					$msgHlpr[3] = 'eergisteren';
				}
				
				if(!isset($msgHlpr[3])){
					$msgHlpr[4] = $eDate->dayToString();

					if($eDate->isInNextWeek()){
						$msgHlpr[3] = 'volgende week ' . $msgHlpr[4];
					}

					if($eDate->isInPrevWeek()){
						$msgHlpr[3] = 'vorige week ' . $msgHlpr[4];
					}

					if(!$eDate->isInCurrentYear()){
						$msgHlpr[3] = $msgHlpr[4] . ' ' . $eDate->getDay() . ' ' . $eDate->getMonthString() . ' ' . $eDate->getYear();
					} else if(!$eDate->isInCurrentWeek()){
						$msgHlpr[3] = $msgHlpr[4] . ' ' . $eDate->getDay() . ' ' . $eDate->getMonthString();
					}
				}
				
				// Lets not show "today" twice
				if($a['endDate'] === $a['date']){
					unset($msgHlpr[3]);
					unset($msgHlpr[4]);
				}
			}
			
			// Get reaction count (improve me this should be baked into the main query!)
			// $a['reactionCount'] = $this->readActivityReactionCount($a['activityId']);
			
			return $a;
		}
		
		public function readUserStream($userId, $filter, $limit, $date){
			if($limit >= 350){
				$limit = 350;
			}
			
			$query = '
				SELECT
					A.id as activityId, A.date, A.time, A.endDate, A.endTime,
					A.destType, A.destId, A.createdOn, A.createdBy,
					T.id as tagId, T.title,
					U.id as userId, U.name as userName
				FROM
					activitiesUsersLink AL
				JOIN
					activities A
				ON
					A.id = AL.activityId
				JOIN
					users U
				ON
					U.id = AL.userId
				LEFT JOIN
					activitiesTags T
				ON
					T.id = A.tagId
				WHERE
					AL.userId = :userId
				AND
					AL.accepted = 1
			';
			
			$queryFilter = $this->getQueryFilter($filter);
			
			// We have to call the function prepare, because the mysql database class
			// does not support bind values (we need this to pass through the limit as int.
			$stmt = $this->db->prepare($query . $queryFilter . 'ORDER BY A.id DESC LIMIT :limit');
			$stmt->setFetchMode(PDO::FETCH_ASSOC);
			$stmt->bindValue('limit', (int)$limit, PDO::PARAM_INT);
			$stmt->bindValue('userId', $userId);

			
			// If the filter is date...
			if($filter === 'date'){
				$stmt->bindValue('date', $date);
			}
				
			$stmt->execute();
			$activities = $stmt->fetchAll();
			
			if(count($activities) > 0){
				
				$users = new Users();
				$locations = new Locations();
				
				// Get all the other users on the activity
				foreach($activities as &$a){
					$activityWithWho = $this->db->query('
						SELECT
							U.id as userId,
							U.name as userName
						FROM
							activitiesUsersLink AL
						LEFT JOIN
							users U
						ON
							U.id = AL.userId
						WHERE
							AL.accepted = 1
						AND
							AL.activityId = ?
						AND
							AL.userId != ?
					', array($a['activityId'], $userId));
					
					if($activityWithWho['rowCount'] > 0){
						$a['withWho'] = $activityWithWho['result'];
					}
					
					// Get the object of the activity.
					$obj =& $a['object'];
					
					// If the object was type 1 (company) get the company.
					if($a['destType'] === '1'){
						$obj = $locations->readCompany($a['destId']);
						
					// Get friend.
					} else if($a['destType'] === '2'){
						if($users->exists($a['destId'])){
							$obj = $users->read($a['destId'], array('id', 'name'));
						} else {
							$obj = $users->readUserFriend(data('fb')->user, $a['destId']);
						}
					
					// Get city.
					} else if($a['destType'] === '3'){
						$obj = $locations->readCity($a['destId']);
					}
					
					$a = $this->attachMessageHelper($a);
				}
			}
			
			return $activities;
		}
	}
	
	/*
		// The field selection is always the same, except for the statistics query.
			$queryFieldSelection = '
				SELECT 
					H.id, H.userId, H.date, H.time, H.endDate, H.endTime, H.destinationObjectId, H.destinationObjectType, H.tag,
					U.id as userId, U.firstName, U.name as userName,
					T.id as tagId, T.name as tagName
			';
			
			// The field selection for the stats query is alwyas the same.
			$statsQueryFieldSelection = "
				SELECT
					(SUM(CASE WHEN U.sex ='male' THEN 1 ELSE 0 END)) as males,
					(SUM(CASE WHEN U.sex ='female' THEN 1 ELSE 0 END)) as females,
					(SUM(CASE WHEN U.relationShipStatus ='single' THEN 1 ELSE 0 END)) as singles,
					COUNT(*) as count
			";
			
			// Limit part of the query.
			$queryLimit = '
				LIMIT :limit
			';
			
			$queryFilter = '';
			
			// Lets attach the date filter.
			switch($filter){
				case 'mostRecent':
					break;
				case 'today':
					$queryFilter = ' AND DATE(H.date) = DATE(CURDATE())';
					break;
				case 'tomorrow':
					$queryFilter = ' AND DATE(H.date) = (CURDATE() + INTERVAL 1 DAY)';
					break;
				case 'yesterday':
					$queryFilter = ' AND DATE(H.date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)';
					break;
				case 'nextWeekend':
					$queryFilter = " AND UNIX_TIMESTAMP(H.DATE) BETWEEN '" . strtotime('next saturday') . "' AND '" . (strtotime('next monday') - 1) . "'";
					break;
				case 'prevWeekend':
					$queryFilter = " AND UNIX_TIMESTAMP(H.DATE) BETWEEN '" . strtotime('previous saturday') . "' AND '" . (strtotime('previous monday') - 1) . "'";
					break;
				case 'date':
					$queryFilter = ' AND DATE(H.date) = DATE(:date)';
					break;
					
				// If the filter was unknown, just return null.
				default:
					return null;
			}
			
			$extraFilter = '';
			
			// Lets not display anything at all.
			if($extraFilters['displayMales'] === 'false' && $extraFilters['displayFemales'] === 'false'){
				return null;
			}
			
			// Only show males...
			if($extraFilters['displayMales'] === 'true' && $extraFilters['displayFemales'] === 'false'){
				$extraFilter = " AND U.sex = 'male'";
			// Display all.
			} else 
			if($extraFilters['displayMales'] === 'true' && $extraFilters['displayFemales'] === 'true'){
				// Do nothing (default is show all sex)
			// Display only females.
			} else
			if($extraFilters['displayMales'] === 'false' && $extraFilters['displayFemales'] === 'true'){
				$extraFilter = " AND U.sex = 'female'";
			}
			
			// Display singles only: NOT FORGET .= because we can COMBINE all those filters.
			if($extraFilters['displaySinglesOnly'] === 'true'){
				$extraFilter .= " AND U.relationshipStatus = 'single'";
			}
			
			$query = '';
			$statsQuery = '';
			$parameterId = '';
			$order = 'ORDER BY H.createdOn DESC';
			
			// If we are getting the stream of an object (user, city or company) ...
			if($objType !== null){
			
				// If we are getting the stream of an CITY or COMPANY
				if($objType === 1 || $objType === 3){
				
					// Display everyone.
					if($extraFilters['displayFriendsOnly'] === 'false'){
						$query = $queryFieldSelection . '
							FROM 
								happenings H
							JOIN
								users U
							ON
								U.id = H.userId
							LEFT JOIN
								happeningsTags T
							ON
								H.tag = T.id
							WHERE
								H.destinationObjectId = :id
						' . $queryFilter . $extraFilter . $order . $queryLimit;
						
						$statsQuery = $statsQueryFieldSelection . '
							FROM
								happenings H
							JOIN
								users U
							ON
								U.id = H.userId
							WHERE 
								H.destinationObjectId = :id
						' . $queryFilter . $extraFilter;
					
					// Display friends only.
					} else{
						$query = $queryFieldSelection . '
							FROM 
								usersFacebookFriends UF
							JOIN
								happenings H
							ON
								H.userId = UF.friendUserId
							JOIN 
								users U
							ON
								U.id = H.userId
							LEFT JOIN
								happeningsTags T
							ON
								H.tag = T.id
							WHERE
								UF.userId = :userId
							AND
								H.destinationObjectId = :id
						' . $queryFilter . $extraFilter . $order . $queryLimit;
						
						$statsQuery = $statsQueryFieldSelection . '
							FROM 
								usersFacebookFriends UF
							JOIN
								happenings H
							ON
								H.userId = UF.friendUserId
							JOIN 
								users U
							ON
								U.id = H.userId
							WHERE
								UF.userId = :userId
							AND
								H.destinationObjectId = :id
						' . $queryFilter . $extraFilter;
					}
					
				// If we are getting the stream of a USER
				} else {
					$query = $queryFieldSelection . '
						FROM 
							happenings H
						JOIN 
							users U
						ON
							U.id = H.userId
						LEFT JOIN
							happeningsTags T
						ON
							H.tag = T.id
						WHERE
							H.userId = :id
					' . $queryFilter . $order . $queryLimit;

					$statsQuery = $statsQueryFieldSelection . '
						FROM
							happenings H
						JOIN
							users U
						ON
							U.id = H.userId
						WHERE 
							H.userId = :id
					' . $queryFilter;
				}
				
				$parameterId = $objId;
				
			// We are getting the stream of the homepage.
			} else {
				$query = $queryFieldSelection . '
					FROM 
						usersFacebookFriends UF
					JOIN
						happenings H
					ON
						H.userId = UF.friendUserId
					JOIN 
						users U
					ON
						U.id = H.userId
					LEFT JOIN
						happeningsTags T
					ON
						H.tag = T.id
					WHERE
						UF.userId = :id
				' . $queryFilter . $order . $queryLimit;
				
				$statsQuery = $statsQueryFieldSelection . '
					FROM
						usersFacebookFriends UF
					JOIN
						happenings H
					ON
						H.userId = UF.friendUserId
					JOIN
						users U
					ON
						U.id = H.userId
					WHERE
						UF.userId = :id
				' . $queryFilter;
				
				$parameterId = $userId;
			}

			// Here we are not using the query method in our Mysql_Database class since the limit must be 
			// casted to int with PDO::PARAM_INT else it will still be casted to a string an enquoted, which will return a query error
			// LIMIT '100' is not correct.
			$stmt = $this->db->prepare($query);
			$stmt->setFetchMode(PDO::FETCH_ASSOC);
			$stmt->bindValue('limit', (int)$limit, PDO::PARAM_INT);
			$stmt->bindValue('id', $parameterId);
			
			// Lets not forget to add another parameter if we are showing friends only.
			if($extraFilters['displayFriendsOnly'] === 'true'){
				$stmt->bindValue('userId', $userId);
			}
			
			if($filter === 'date'){
				$stmt->bindValue('date', $date);
			}
				
			$stmt->execute();
			$activities = $stmt->fetchAll();
			
			// Now get the statistics of the stream that the user is getting.
			$stmt = $this->db->prepare($statsQuery);
			$stmt->setFetchMode(PDO::FETCH_ASSOC);
			$stmt->bindValue('id', $parameterId);
			
			// Lets not forget to add another parameter if we are showing friends only.
			if($extraFilters['displayFriendsOnly'] === 'true'){
				$stmt->bindValue('userId', $userId);
			}
			
			if($filter === 'date'){
				$stmt->bindValue('date', $date);
			}
			
			$stmt->execute();
			$stats = $stmt->fetchAll();
			
			// 
			if($activities){
				foreach($activities as &$a){
					$withWhoStmt = $this->db->query('
						SELECT 
							`id`, `name`
						FROM
							`happeningsWithWho`
						WHERE
							`happeningId` = ?
					', array($a['id']));
	
					
					if($withWhoStmt['rowCount'] > 0){
						$a['withWho'] = $withWhoStmt['result'];
					}
				}
				
				return array('activities' => $activities, 'stats' => $stats[0]);
			}
			
			return false;
*/

// File end.